package com.collectplus.express;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.Selection;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.model.Const.RequestCode;
import com.shouhuobao.bhi.login.LoginActivity;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import droid.frame.activity.base.FrameBaseActivity;
import droid.frame.activity.title.AppTitle;
import droid.frame.activity.title.TitleMgr;
import droid.frame.fragment.FragmentMgr;
import droid.frame.ui.dialog.AppLoading;
import droid.frame.utils.android.Log;

/**
 * @author coffee <br>
 * 2016-3-15下午2:54:44
 */
public abstract class BaseActivity2 extends FrameBaseActivity {

    private AppTitle appTitle;

    protected SwipeRefreshLayout mSwipeLayout;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setStatusBarColor(R.color.app_status);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        appTitle = new TitleMgr(getContext());
        appTitle.initTitle();
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    protected void onRefreshComplete() {
        if (mSwipeLayout != null) {
            getContext().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mSwipeLayout.setRefreshing(false);
                }
            });
        }
    }

    public AppTitle getAppTitle() {
        return appTitle;
    }

    public void setAppTitle(AppTitle appTitle) {
        this.appTitle = appTitle;
    }

    public void setTitleBackground(int backgroundRes) {
        View layout = findViewById(R.id.app_title_layout);
        layout.setBackgroundResource(backgroundRes);
    }

    public void setTitleBackgroundColor(int backgroundColor) {
        View layout = findViewById(R.id.app_title_layout);
        layout.setBackgroundColor(backgroundColor);
    }

    // 跳转到主页面
    public void goMainFragmentActivity() {
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setClass(getContext(), MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();// 关闭当前Activity
            }
        });
    }

    private AppLoading loading;

    public void showLoadingDialog(final String dialogMessage) {
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loading != null && loading.isShowing()) {
                    loading.setMessage(dialogMessage);
                    return;
                } else {
                    loading = new AppLoading(getContext());
                    loading.setMessage(dialogMessage);
                    loading.show();
                }
            }
        });
    }

    protected void cancelLoadingDialog() {
        getContext().runOnUiThread(new Runnable() {
            public void run() {
                if (loading != null) {
                    loading.dismiss();
                }
            }
        });
    }

    public void setButtonEnableStyle(Button button, boolean enable) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.app_button_selector);
            button.setTextColor(getResources().getColorStateList(R.color.app_buttoncolor_selector));
        } else {
            button.setBackgroundResource(R.drawable.app_button_bg_disable);
            button.setTextColor(getResources().getColor(R.color.white));
        }
        button.setPadding(left, top, right, bottom);
    }

    public boolean isEmpty(Object str) {
        if (str == null || str.toString().trim().length() == 0 || "null".equals(str.toString().trim())) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isNotEmpty(Object str) {
        return !isEmpty(str);
    }

    //    @Override
    //    public boolean handleMessage(Message msg) {
    //        switch (msg.what) {
    //            case MsgID.self_bagcode_check:
    //                if (isResume) {
    //                    cancelLoadingDialog();
    //                    AppResult<BagBean> result = JSON.parser(msg.obj, BagBean.class);
    //                    if (result.isSuccess() && result.getResult() != null) {
    //                        Intent intent = new Intent();
    //                        intent.setClass(getContext(), SelfFormInfoActivity.class);
    //                        intent.putExtra("bag", result.getResult());
    //                        startActivity(intent);
    //                    } else {
    //                        showToast(result.getMessage());
    //                    }
    //                }
    //                return false;
    //            default:
    //                return super.handleMessage(msg);
    //        }
    //
    //    }

    private Class<?> nextActivity = null;
    private Intent oldIntent;

    public void startActivityWhenLogin(Class<?> activityClass, String... params) {
        nextActivity = activityClass;
        Intent intent = new Intent();
        if (AppCache.isLogin() == false) {
            intent.setClass(getContext(), LoginActivity.class);
        } else {
            intent.setClass(getContext(), nextActivity);
        }
        for (int i = 0; i < params.length; i++) {
            if (i + 1 < params.length) {
                intent.putExtra(params[i].toString(), params[i + 1]);
            }
        }
        oldIntent = intent;
        startActivityForResult(intent, RequestCode.login);
    }

    @SuppressLint("RestrictedApi")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        FragmentManager fm = getSupportFragmentManager();
//        int index = requestCode >> 16;
//        if (index != 0) {
//            index--;
//            if (fm.getFragments() == null || index < 0
//                    || index >= fm.getFragments().size()) {
//                Log.d("BaseActivity2", "Activity result fragment index out of range: 0x" + Integer.toHexString(requestCode));
//                return;
//            }
//            Fragment frag = fm.getFragments().get(index);
//            if (frag == null) {
//                Log.d("BaseActivity2", "Activity result no fragment exists for index: 0x"
//                        + Integer.toHexString(requestCode));
//            } else {
//                handleResult(frag, requestCode, resultCode, data);
//            }
//            return;
//        }
        // 登录
        if (requestCode == RequestCode.login && resultCode == Activity.RESULT_OK) {
            Intent intent = new Intent();
            intent.setClass(getContext(), nextActivity);
            intent.putExtras(oldIntent);
            startActivity(intent);
        }
        // 扫描袋子条形码
        else if (requestCode == RequestCode.scan_bag && resultCode == RESULT_OK) {
            String code = data.getStringExtra("result");
            int index1 = code.lastIndexOf("=");
            String code2;
            if (index1 > -1) {
                code2 = code.substring(index1 + 1, code.length());
            } else {
                code2 = code;
            }
            showLoadingDialog("数据校验");
            AppHttp.getInstance().selfBagCodeCheck(code2);
        }
    }

//    /**
//     * 递归调用，对所有子Fragement生效
//     *
//     * @param frag
//     * @param requestCode
//     * @param resultCode
//     * @param data
//     */
//    private void handleResult(Fragment frag, int requestCode, int resultCode,
//                              Intent data) {
//        frag.onActivityResult(requestCode & 0xffff, resultCode, data);
//        @SuppressLint("RestrictedApi")
//        List<Fragment> frags = frag.getChildFragmentManager().getFragments();
//        if (frags != null) {
//            for (Fragment f : frags) {
//                if (f != null)
//                    handleResult(f, requestCode, resultCode, data);
//            }
//        }
//    }

    public void startActivity(Class<?> classActivity) {
        Intent intent = new Intent();
        intent.setClass(getContext(), classActivity);
        startActivity(intent);
    }

    /**
     * 判断用户是否登录
     *
     * @return
     */
    public boolean isLogin() {
        return AppCache.isLogin();
    }

    /**
     * 移动光标到最后
     */
    public void setCursorToLast(EditText editText) {
        // 光标移动到最后
        Editable editable = editText.getEditableText();
        Selection.setSelection(editable, editable.length());
    }

    @Override
    protected void onDestroy() {
        FragmentMgr.getInstance(this).onDestroy(this);
        RefWatcher refWatcher = ExpressApplication.getRefWatcher(getApplicationContext());
        refWatcher.watch(this);
        super.onDestroy();
    }
}
